/*
 * Copyright (C) 2013 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * FMoveToPostponed.java
 *
 * Created on Mar 25, 2013, 4:44:32 PM
 */
package ru.apertum.qsystem.client.forms;

import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import ru.apertum.qsystem.QSystem;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.LayoutStyle;
import javax.swing.SpinnerDateModel;
import javax.swing.WindowConstants;
import javax.swing.border.MatteBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.text.DateFormatter;
import java.awt.Color;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.ResourceBundle;

/**
 * Диалог для откладывания в отложенные.
 *
 * @author Evgeniy Egorov
 */
@SuppressWarnings({"squid:S1192", "squid:S1172", "squid:S1450", "squid:S1604", "squid:S1161", "squid:MaximumInheritanceDepth"})
public class FMoveToPostponed extends javax.swing.JDialog {

    /**
     * Результат.
     */
    private boolean ok;
    private static ResourceMap localeMap = null;

    private static String getLocaleMessage(String key) {
        if (localeMap == null) {
            localeMap = Application.getInstance(QSystem.class).getContext().getResourceMap(FMoveToPostponed.class);
        }
        return localeMap.getString(key);
    }

    /**
     * Creates new form FMoveToPostponed.
     */
    public FMoveToPostponed(java.awt.Frame parent, boolean modal, Object[] results) {
        super(parent, modal);
        initComponents();
        comboBoxPeriod.setModel(new javax.swing.DefaultComboBoxModel(getLocaleMessage("conboBox.periods").split(",")));
        comboBoxResults.setModel(new javax.swing.DefaultComboBoxModel(results));
        cbOnlyMine.setSelected(false);

        final JSpinner.DateEditor editor = new JSpinner.DateEditor(spinnerTime, "HH:mm");
        final DateFormatter formatter = (DateFormatter) editor.getTextField().getFormatter();
        formatter.setAllowsInvalid(false); // this makes what you want
        formatter.setOverwriteMode(true);

        spinnerTime.setEditor(editor);
        final GregorianCalendar calendar = new GregorianCalendar();
        calendar.add(GregorianCalendar.MINUTE, 35);
        calendar.set(GregorianCalendar.YEAR, 0);
        calendar.set(GregorianCalendar.MONTH, 0);
        calendar.set(GregorianCalendar.DAY_OF_YEAR, 0);
        spinnerTime.setValue(calendar.getTime());

        spinnerTime.addChangeListener((ChangeEvent ce) -> {
            long date = (((Date) spinnerTime.getValue()).getTime() - (System.currentTimeMillis() % (1000 * 60 * 60 * 24)));
            if (date < 0) {
                final GregorianCalendar calendar1 = new GregorianCalendar();
                calendar1.add(GregorianCalendar.MINUTE, 35);
                calendar1.set(GregorianCalendar.YEAR, 0);
                calendar1.set(GregorianCalendar.MONTH, 0);
                calendar1.set(GregorianCalendar.DAY_OF_YEAR, 0);
                spinnerTime.setValue(calendar1.getTime());
            }
        });

        rbPeriodActionPerformed(null);
    }

    /**
     * Получаем период откладывания из диалога.
     *
     * @return минуты.
     */
    public int getPeriod() {
        return rbPeriod.isSelected()
                ? comboBoxPeriod.getSelectedIndex() * 5
                : ((int) (((Date) spinnerTime.getValue()).getTime() - (System.currentTimeMillis() % (1000 * 60 * 60 * 24))) / 1000 / 60 + 1);
    }

    public String getResult() {
        return (String) comboBoxResults.getModel().getSelectedItem();
    }

    public boolean isMine() {
        return cbOnlyMine.isSelected() && comboBoxPeriod.getSelectedIndex() == 0;
    }

    public boolean isOK() {
        return ok;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    private void initComponents() {
        ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.client.forms.resources.FMoveToPostponed");
        jPanel1 = new JPanel();
        labelResult = new JLabel();
        comboBoxResults = new JComboBox<>();
        comboBoxPeriod = new JComboBox();
        rbPeriod = new JRadioButton();
        rbTime = new JRadioButton();
        spinnerTime = new JSpinner();
        cbOnlyMine = new JCheckBox();
        buttonOK = new JButton();
        buttonCancel = new JButton();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(bundle.getString("Form.title"));
        setModal(true);
        setName("Form");
        setResizable(false);
        var contentPane = getContentPane();

        //======== jPanel1 ========
        {
            jPanel1.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
            jPanel1.setName("jPanel1");

            //---- labelResult ----
            labelResult.setText(bundle.getString("labelResult.text"));
            labelResult.setName("labelResult");

            //---- comboBoxResults ----
            comboBoxResults.setModel(new DefaultComboBoxModel<>(new String[]{
                    "Item 1",
                    "Item 2",
                    "Item 3",
                    "Item 4"
            }));
            comboBoxResults.setName("comboBoxResults");

            //---- comboBoxPeriod ----
            comboBoxPeriod.setName("comboBoxPeriod");
            comboBoxPeriod.addActionListener(e -> comboBoxPeriodActionPerformed(e));

            //---- rbPeriod ----
            rbPeriod.setSelected(true);
            rbPeriod.setName("rbPeriod");
            rbPeriod.addActionListener(e -> rbPeriodActionPerformed(e));

            //---- rbTime ----
            rbTime.setText(bundle.getString("rbTime.text"));
            rbTime.setName("rbTime");
            rbTime.addActionListener(e -> rbPeriodActionPerformed(e));

            //---- spinnerTime ----
            spinnerTime.setModel(new SpinnerDateModel(new java.util.Date((System.currentTimeMillis() / 60000) * 60000), null, null, java.util.Calendar.MINUTE));
            spinnerTime.setName("spinnerTime");

            //---- cbOnlyMine ----
            cbOnlyMine.setText(bundle.getString("cbOnlyMine.text"));
            cbOnlyMine.setName("cbOnlyMine");

            GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                    jPanel1Layout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGap(0, 0, Short.MAX_VALUE)
                                                    .addComponent(cbOnlyMine))
                                            .addComponent(comboBoxResults, GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                                            .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                                    .addComponent(rbPeriod)
                                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                                    .addComponent(comboBoxPeriod))
                                            .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                            .addComponent(labelResult, GroupLayout.Alignment.LEADING)
                                                            .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                                                    .addComponent(rbTime)
                                                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                                                    .addComponent(spinnerTime, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                                                    .addGap(0, 0, Short.MAX_VALUE)))
                                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                    jPanel1Layout.createParallelGroup()
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(labelResult)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(comboBoxResults, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                            .addComponent(comboBoxPeriod)
                                            .addComponent(rbPeriod, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                            .addComponent(rbTime)
                                            .addComponent(spinnerTime, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(cbOnlyMine)
                                    .addContainerGap(20, Short.MAX_VALUE))
            );
        }

        //---- buttonOK ----
        buttonOK.setText(bundle.getString("buttonOK.text"));
        buttonOK.setName("buttonOK");
        buttonOK.addActionListener(e -> buttonOKActionPerformed(e));

        //---- buttonCancel ----
        buttonCancel.setText(bundle.getString("buttonCancel.text"));
        buttonCancel.setName("buttonCancel");
        buttonCancel.addActionListener(e -> buttonCancelActionPerformed(e));

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
                contentPaneLayout.createParallelGroup()
                        .addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
                                .addContainerGap(253, Short.MAX_VALUE)
                                .addComponent(buttonOK)
                                .addGap(18, 18, 18)
                                .addComponent(buttonCancel)
                                .addContainerGap())
                        .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        contentPaneLayout.setVerticalGroup(
                contentPaneLayout.createParallelGroup()
                        .addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
                                .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                        .addComponent(buttonCancel)
                                        .addComponent(buttonOK))
                                .addContainerGap())
        );
        pack();
        setLocationRelativeTo(getOwner());

        //---- bgPostpone ----
        var bgPostpone = new ButtonGroup();
        bgPostpone.add(rbPeriod);
        bgPostpone.add(rbTime);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        ok = true;
        setVisible(false);
    }//GEN-LAST:event_buttonOKActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        ok = false;
        setVisible(false);
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void comboBoxPeriodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxPeriodActionPerformed
        cbOnlyMine.setVisible(comboBoxPeriod.getSelectedIndex() == 0);
    }//GEN-LAST:event_comboBoxPeriodActionPerformed

    private void rbPeriodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbPeriodActionPerformed
        comboBoxPeriod.setEnabled(rbPeriod.isSelected());
        spinnerTime.setEnabled(rbTime.isSelected());
    }//GEN-LAST:event_rbPeriodActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner non-commercial license
    private JPanel jPanel1;
    private JLabel labelResult;
    private JComboBox<String> comboBoxResults;
    private JComboBox comboBoxPeriod;
    private JRadioButton rbPeriod;
    private JRadioButton rbTime;
    private JSpinner spinnerTime;
    private JCheckBox cbOnlyMine;
    private JButton buttonOK;
    private JButton buttonCancel;
    // End of variables declaration//GEN-END:variables
}
